package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Query;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.RequestServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 搜索申请列表
 * <p>
 * 首页搜索、每个栏目里面的搜索、筛选都是它
 */
@WebServlet("/searchRequestList")
public class SearchRequestList extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(SearchRequestList.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 无处理权限的普通人：3(我申请的);6(抄送我的,我归档的);7(我参与的);
     * boss : 3,4,5,6,7,8都走了一遍;其中3,4,8传的applicant都是自己,5传的是-1：搜的是下属申请的
     * 数据格式:{
     * "keywords": "报销(选填)",
     * "page": "1（必填）",
     * "dataNum": "2（必填）",
     * "searchStartTime": "2016-07-11(选填)",
     * "searchEndTime": "2016-07-16(选填)",
     * "ancestorIds": "xx,xx,xx（原始模板ID，多选，和右边的单选不能共存）(选填)",
     * "ancestorId": "id(精确查找模板的参数，传入模板列表里的ancestorId) (选填)",
     * "applicant": "指定搜某人的(选填，在某人申请的中，作为申请人存在) (选填)",
     * "searchRange": "通常作为申请人存在，xx,xx,xx(选填)",
     * "searchType": " 搜索类型：1.抄送我的未归档，2.我已归档，3.某人申请的，4.某人处理的, 5.搜索某人的(3和4),6.搜索抄送我的和我归档的(1和2),7:我参与的,8:待处理的（必填）",
     * "currentStatus":"指定的finished状态，xx,xx,xx",
     * "orderBy":"1:申请时间，2：最终批准时间，3：归档时间，不给则按申请时间排序，String类型，预防以后有什么变动"
     * }
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            User user = getReqUser(req);

            Request request = getRequest(req);

            RequestServicePrx requestServicePrx = ServantUtils.getObject(RequestServicePrx.class);
            Query query = getQuery(req, user, request);
            if (Utils.isNull(query.getSearchType())) {
                throw new RpcServerLogicalException(1, "searchType不能为空");
            }
            List<Request> list = requestServicePrx.searchRequest(query);

            // 替换新版本的值
            ApprovalUtils.replaceNewExpenseValue(list);

            returnResult(resp, list);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    @Override
    Query getQuery(HttpServletRequest req, User user, Request request) {
        Query query = super.getQuery(req, user, request);
        query.setSearchType(request.getSearchType());
        query.setKeywords(request.getKeywords());
        if (Utils.isNotNull(request.getAncestorId()) && request.getAncestorId() > 0) {
            query.setAncestorIds(String.valueOf(request.getAncestorId()));
        } else {
            query.setAncestorIds(request.getAncestorIds());
        }
        if (StringUtils.isNotBlank(request.getSearchStartTime())) {
            query.setStartDate(request.getSearchStartTime());
        }
        if (StringUtils.isNotBlank(request.getSearchEndTime())) {
            query.setEndDate(request.getSearchEndTime());
        }
        if (StringUtils.isNotBlank(request.getSearchRange())) {
            query.setApplicants(request.getSearchRange());
        }
        return query;
    }

    private void returnResult(HttpServletResponse resp, List<Request> requests) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "获得成功");
        jsonObject.put("item", requests);

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    private Request getRequest(HttpServletRequest req) throws ServletException, IOException {
        String reqBody = getContent(req);
        logger.info("json参数 {}", reqBody);

        Request request;
        try {
            request = JSONObject.parseObject(reqBody, Request.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
        }
        return request;
    }

}
